import 'package:app/api/api.dart';
import 'package:app/pages/index/widget/bottomNavs.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class IndexController extends GetxController {
  final ApiRepository apiRepository;
  IndexController({required this.apiRepository});

  var currentTab = MainTabs.home.obs;
  int currentIndex = 0;

  late HomePage homeTab;
  late DiscoverPage discoverTab;
  late MessagePage messageTab;
  late MePage meTab;
  late ScrollController HomeControllerDropDown = new ScrollController();

  //页面状态保持
  //第一步 声明pageController
  late PageController pageController;

  //页面缓存

  var presenters = [].obs;
  var wonderfulList = [].obs;
  var numericalList = [].obs;
  var commentsList = [].obs;

  @override
  void onInit() async {
    super.onInit();
    homeTab = HomePage();
    discoverTab = DiscoverPage();
    messageTab = MessagePage();
    meTab = MePage();
    Presenters();
    getWonderfulList();
    getNumericalList();

    //第二步 初始化pagecontroller

    pageController = PageController(initialPage: currentIndex);
    HomeControllerDropDown.addListener(() {
      if (HomeControllerDropDown.position.pixels ==
          HomeControllerDropDown.position.maxScrollExtent) {
        print("上拉加载更多");
      }
    });
  }

  Future<void> Presenters() async {
    var res = await apiRepository.getPresenters();

    if (res!.data.length > 0) {
      presenters.assignAll(res.data);
      update();
    }
  }

  Future<void> getWonderfulList() async {
    var res = await apiRepository.getWonderfulList();

    if (res!.data.length > 0) {
      wonderfulList.assignAll(res.data);
      update();
    }
  }

  Future<void> getNumericalList() async {
    var res = await apiRepository.getNumericalList();
    if (res!.data.length > 0) {
      numericalList.assignAll(res.data);
    }
  }

  Future<void> getComments() async {
    var res = await apiRepository.getComments();
    if (res!.data.comments.length > 0) {
      commentsList.assignAll(res.data.comments);
    }
  }

  void switchTab(index) {
    currentIndex = index;
    var tab = _getCurrentTab(index);
    currentTab.value = tab;
  }

  int getCurrentIndex(MainTabs tab) {
    switch (tab) {
      case MainTabs.home:
        return 0;
      case MainTabs.discover:
        return 1;
      case MainTabs.message:
        return 3;
      case MainTabs.me:
        return 4;
      default:
        return 0;
    }
  }

  MainTabs _getCurrentTab(index) {
    switch (index) {
      case 0:
        return MainTabs.home;
      case 1:
        return MainTabs.discover;
      case 2:
        Get.toNamed("/home/publishPage");
        return currentTab.value;
      case 3:
        return MainTabs.message;
      case 4:
        return MainTabs.me;
      default:
        return MainTabs.home;
    }
  }
}
